import execjs
import os,re,xlwt
#创建一个PHP类，

import subprocess
import json,time
class PHP(object):
    """This class provides a stupid simple interface to PHP code."""
    
    def __init__(self, filenameAddr):
        self.filenameAddr = filenameAddr #执行的php文件

    def __submit(self):
        proc = subprocess.Popen(
                    ["php",self.filenameAddr],
                    stdin=subprocess.PIPE,
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE,
                    shell=True
                    )
        #proc.stdin.write('<?php\n'.encode())
        #proc.stdin.write('echo json_encode('.encode())
        #proc.stdin.write(code.encode())
        #proc.stdin.write(')?>\n'.encode())
        out,err=proc.communicate()
        out = json.loads(out.decode())  #返回的是字符串,转为json对象
        return out

    def get_raw(self, code):
        """Given a code block, invoke the code and return the raw result as a string."""
        out = self.__submit(code)
        return out

    def get(self):
        """Given a code block that emits json, invoke the code and interpret the result as a Python value."""
        out = self.__submit()
        return out

    def get_one(self, code):
        """Given a code block that emits multiple json values (one per line), yield the next value."""
        out = self.__submit(code)
        for line in out:
            line = line.strip()
            if line:
                yield json.loads(line)

book = xlwt.Workbook(encoding='utf-8')  
sheet1 = book.add_sheet('sheet1')
style = xlwt.easyxf('alignment: horz center, vert center')      #设置样式，居中
sheet1.col(0).width =7680  #30个字符宽度，一个字节为256
sheet1.col(1).width =30000  # 
gen_addr = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
fileDir = os.path.join(gen_addr,'lang','en')
'''
fileList = os.listdir(fileDir)
write_row = 0 #写的行数
for file0 in fileList:
    if file0 == 'validate_en.js':
        continue
    file0 = os.path.join(gen_addr,'lang','en', file0)
    print(file0)
    file_ext = file0.split('.')[1]  #获取文件后缀名 js  php
    with open(file0,'r',encoding='utf-8') as fo:
        ret_data = fo.read()
        #print(ret_data)
        if file_ext == 'js':
            #函数名称
            func_name = ''
            ret_data = re.findall('({[^\{\}]*})',ret_data)
            ret_data = ret_data[0]
            ret_data = execjs.eval(ret_data)
            
        elif file_ext == 'php':
            lines = fo.seek(0,0)  #指针重置到文件开头
            lines = fo.readlines()  #读取所有行
            len_lines = len(lines)  #文件的行数
            if  not '?>' in lines[len_lines-1]:   #判断php文件末尾是否加了?>
                ret_data = ret_data + '?>'
            
            #函数名称
            tmp_php = os.path.join(gen_addr,'ci18n','tmp_php.php')
            func_name = re.findall('function ([\w]*)',ret_data)[0]
            with open(tmp_php, 'w', encoding='utf-8') as fi:
                fi.write(ret_data)
                fi.write('\n<?php\n')
                fi.write('echo json_encode('+func_name+'())\n')
                fi.write('?>')
            php1 =PHP(tmp_php) 
            ret_data = php1.get()
        
        #print(ret_data)
    for index,key in enumerate(ret_data):
        print(write_row,key,func_name)
        sheet1.write(write_row,0,key)
        sheet1.write(write_row,1,ret_data[key])
        write_row += 1

#excel文件保存地址
excel_addr = os.path.join(gen_addr,'ci18n','test')
book.save(excel_addr+'.xls')
'''

#先读一个文件
def readFileData(file0):
    #判断file0文件是否
    if not os.path.exists(file0):
        return False
    file_ext = file0.split('.')[1]  #获取文件后缀名 js  php
    with open(file0,'r', encoding='utf-8') as fo:
        ret_data = fo.read()
        #print(ret_data)
        if file_ext == 'js':
            #函数名称
            func_name = ''
            ret_data = re.findall('({[^\{\}]*})',ret_data)
            ret_data = ret_data[0]
            ret_data = execjs.get(execjs.runtime_names.JScript).eval(ret_data)
            
        elif file_ext == 'php':
            lines = fo.seek(0,0)  #指针重置到文件开头
            lines = fo.readlines()  #读取所有行
            len_lines = len(lines)  #文件的行数
            if  not '?>' in lines[len_lines-1]:   #判断php文件末尾是否加了?>
                ret_data = ret_data + '?>'
            
            #函数名称
            tmp_php = os.path.join(gen_addr,'ci18n','tmp_php.php')
            func_name = re.findall('function ([\w]*)',ret_data)[0]
            with open(tmp_php, 'w', encoding='utf-8') as fi:
                fi.write(ret_data)
                fi.write('\n<?php\n')
                fi.write('echo json_encode('+func_name+'())\n')
                fi.write('?>')
            php1 =PHP(tmp_php) 
            ret_data = php1.get()
    return (ret_data, func_name)


file1 = os.path.join(gen_addr,'lang','en', 'base_en.js')
file2 = os.path.join(gen_addr,'lang','zh-cn', 'base_zh-cn1.js')
ret_data1, fun_name = readFileData(file1)

ret_data2 = readFileData(file2)
if ret_data2 == False:
    print('目录不存在:',time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))
'''
#print(len(ret_data1),len(ret_data2))
for index,key1 in enumerate(ret_data1):
    sheet1.write(index,0,key1)
    if key1 in ret_data2:
        sheet1.write(index,1,ret_data2[key1])
    else:
        sheet1.write(index,1,'')
    sheet1.write(index,2,fun_name)
#excel文件保存地址
excel_addr = os.path.join(gen_addr,'ci18n','test')
book.save(excel_addr+'.xls')
'''
'''
for index,key in enumerate(ret_data):
    print(index,key,func_name)
    sheet1.write(index,0,key)
    sheet1.write(index,1,ret_data[key])
'''